<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               :row-class-name="rowClassName"
               :cell-class-name="rowClassName"
               @on-load="onLoad">
      <template  #menu-left>
        <el-button type="primary" icon="el-icon-plus" v-if="permission.work_price_add" @click="handleAdd">新 增
        </el-button>
<!--        <el-button type="danger"-->
<!--                   icon="el-icon-delete"-->
<!--                   v-if="permission.work_price_delete"-->
<!--                   @click="handleDelete">删 除-->
<!--        </el-button>-->
        <el-button
                type="warning"
                icon="el-icon-download"
                @click="handleExport"
        >导出
        </el-button>
      </template>

      <template #activeDate-search="{ disabled, size }">
        <!--<div style="display: flex;flex-direction: start;">-->
          <!--<el-select v-model="search.salesDateRule" placeholder="比较" filterable clearable>-->
            <!--<el-option label="" value=""></el-option>-->
            <!--<el-option value=">" label="大于">大于 </el-option>-->
            <!--<el-option value=">=" label="大于等于">大于等于 </el-option>-->
            <!--<el-option value="=" label="等于">等于 </el-option>-->
            <!--<el-option value="!=" label="不等于">不等于 </el-option>-->
            <!--<el-option value="<=" label="小于等于">小于等于 </el-option>-->
            <!--<el-option value="<" label="小于">小于 </el-option>-->
          <!--</el-select>-->
          <!--<el-date-picker-->
                  <!--size="default"-->
                  <!--v-model="search.salesDateSearch"-->
                  <!--type="month"-->
                  <!--:format="dateFormat"-->
                  <!--:value-format="dateFormat"-->
                  <!--:unlink-panels="true"-->
                  <!--clearable-->
                  <!--placeholder="生效日期"-->
                  <!--:picker-options="pickerOptions"-->
          <!--&gt;-->
          <!--</el-date-picker>-->
        <!--</div>-->
        <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.activeDateRange"
                type="monthrange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="生效日期"
                @change="handleDatePickerChange"
                :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>

      <template #menu="{ row, size, type }">
        <el-tooltip content="查看" placement="top">
          <el-button
                  icon="el-icon-view"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleView(row)"
                  v-if="permission.work_price_view"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="复制" placement="top">
          <el-button
                  icon="DocumentCopy"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleCopy(row)"
                  v-if="permission.work_price_edit"
          >
          </el-button>
        </el-tooltip>
<!--        <el-tooltip content="更新单价" placement="top">-->
<!--          <el-button-->
<!--                  icon="FolderChecked"-->
<!--                  link-->
<!--                  :size="size"-->
<!--                  :type="type"-->
<!--                  @click="() => handleEdit(row)"-->
<!--                  v-if="permission.work_price_edit"-->
<!--          >-->
<!--          </el-button>-->
<!--        </el-tooltip>-->
        <el-tooltip content="审核" placement="top" v-if="row.isAssign=='未审核'">
          <el-button
                  icon="EditPen"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rowAudit(row)"
                  v-if="permission.work_price_audit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="无效" placement="top"  v-if="row.isActive=='是'">
          <el-button
                  icon="VideoPause"
                  link
                  :size="size"
                  :type="type"
                  @click="() => updateActive(row)"
                  v-if="permission.work_price_audit"
          >
          </el-button>
        </el-tooltip>
<!--        <el-tooltip content="删除" placement="top" v-if="row.isAssign =='未审核'">-->
<!--          <el-button-->
<!--                  icon="el-icon-delete"-->
<!--                  link-->
<!--                  :size="size"-->
<!--                  :type="type"-->
<!--                  @click="() => rowDel(row)"-->
<!--                  v-if="permission.work_price_delete"-->
<!--          >-->
<!--          </el-button>-->
<!--        </el-tooltip>-->
      </template>
    </avue-crud>
    <work-price-form ref="workPriceForm" @success="refreshChange" ></work-price-form>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove,audit,editPrice,changeStatus, updateActive} from "@/api/anwise/prod/work_price";
  import workPriceForm from './components/work_price_form.vue';
  import {mapGetters} from "vuex";
  import website from '@/config/website';
  import { getToken } from '@/utils/auth';
  import { exportBlob } from '@/api/common';
  import { downloadXls } from '@/utils/util';
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';
  import {userCompany} from "@/api/anwise/common";

  export default {
    components: {
      workPriceForm
    },
    data() {
      return {
        form: {},
        query: {},
        search:{},
          activeDateRange:[],
        loading: true,
        dateFormat:"YYYY-MM",
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: true,
          reserveSelection:true,
          labelWidth: 150,
          indexWidth:100,
          menuWidth: 200,
          addBtn: false,
          editBtn: false,
          viewBtn: false,
          delBtn: false,
          stripe: true,
          searchIndex: 3,
          searchIcon: false,
          searchLabelWidth:110,
          searchEnter:true,
          column: [
            // {
            //   label: "",
            //   prop: "id",
            //   type: "input",
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   hide:true,
            // },
            // {
            //   label: "加工商id",
            //   prop: "supId",
            //   type: "input",
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   hide:true,
            // },
            // {
            //   label: "所属机构id",
            //   prop: "deptId",
            //   type: "input",
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   hide:true,
            // },
            {
              label: "加工商账号",
              prop: "supNo",
              type: "input",
              fixed: true,
              search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请输入加工商账号",
                trigger: "blur"
              }],
            },
            {
              label: "加工商名称",
              prop: "supName",
              type: "input",
              fixed: true,
              search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请输入加工商名称",
                trigger: "blur"
              }],
            },

            {
              label: "物料编号",
              prop: "materialNo",
              type: "input",
              search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请输入物料编号",
                trigger: "blur"
              }],
            },
            {
              label: "物料名称",
              prop: "materialName",
              type: "input",
              search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请输入物料名称",
                trigger: "blur"
              }],
            },
            {
              label: "客户条码",
              prop: "barCode",
              type: "input",
              search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请输入客户条码",
                trigger: "blur"
              }],
            },
            {
              label: "币别",
              prop: "rmb",
              type: "select",
              filterable: true,
              overHidden: true,
              sortable: true,
              width:120,
              dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
              props: {
                label: 'dictValue',
                value: 'dictKey',
              },
              dataType: 'string',
              rules: [{
                required: true,
                message: "请选择币别",
                trigger: "blur"
              }],
            },
            {
              label: "不含税单价",
              prop: "taxExclusivePrice",
              type: "input",
              // search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请输入物料名称",
                trigger: "blur"
              }],
            },
              {
                  label: "加工工序",
                  prop: "workList",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:170,
                  rules: [{
                      required: true,
                      message: "请输入加工工序",
                      trigger: "blur"
                  }],
              },
              {
                  label: "类别",
                  prop: "materialType",
                  type: "select",
                  filterable:true,
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  dicUrl: "/blade-system/dict-biz/dictionary?code=material_s_type",
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: true,
                      message: "请选择类别",
                      trigger: "blur"
                  }],
              },
            {
              label: "是否已审核",
              prop: "isAssign",
              type: "input",
              // search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请输入物料名称",
                trigger: "blur"
              }],
            },
            // {
            //   label: "是否有效",
            //   prop: "isActive",
            //   type: "input",
            //   // search: true,
            //   overHidden: true,
            //   sortable: true,
            //   search:true,
            //   width:130,
            //   rules: [{
            //     required: true,
            //     message: "请输入是否有效",
            //     trigger: "blur"
            //   }],
            // },
              {
                  label: "是否有效",
                  prop: "isActive",
                  type: "select",
                  dicUrl: "/blade-system/dict-biz/dictionary?code=biz_yes_no",
                  filterable: true,
                  overHidden: true,
                  search: true,
                  sortable: true,
                  searchValue: '是',
                  width:150,
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请选择是否有效",
                      trigger: "blur"
                  }],
              },
            {
              label: "生效年月",
              prop: "activeDate",
              type: "month",
              format: "YYYY年MM月",
              valueFormat: "YYYY-MM-DD",
              search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请选择生效年月",
                trigger: "blur"
              }],
            },
            {
              label: "是否已更新",
              prop: "isRenewal",
              type: "input",
              // search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请输入物料名称",
                trigger: "blur"
              }],
            },
            {
              label: "审核人",
              prop: "approver",
              type: "input",
              overHidden: true,
              sortable: true,
              width:130,
              disabled:true,
              rules: [{
                required: false,
                message: "请输入审核人",
                trigger: "blur"
              }],
            },
            {
              label: "审核时间",
              prop: "approverDate",
              type: "date",
              overHidden: true,
              sortable: true,
              width:130,
              disabled:true,
                valueFormat: 'YYYY-MM-DD',
                format:'YYYY-MM-DD',
              rules: [{
                required: false,
                message: "请选择审核时间",
                trigger: "blur"
              }],
            }
            // {
            //   label: "更新人",
            //   prop: "renewalUser",
            //   type: "input",
            //   // search: true,
            //   overHidden: true,
            //   sortable: true,
            //   width:130,
            //   rules: [{
            //     required: true,
            //     message: "请输入物料名称",
            //     trigger: "blur"
            //   }],
            // },
            // {
            //   label: "更新时间",
            //   prop: "renewalDate",
            //   type: "input",
            //   // search: true,
            //   overHidden: true,
            //   sortable: true,
            //   width:130,
            //   rules: [{
            //     required: true,
            //     message: "请输入物料名称",
            //     trigger: "blur"
            //   }],
            // }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.work_price_add, false),
          viewBtn: this.validData(this.permission.work_price_view, false),
          delBtn: this.validData(this.permission.work_price_delete, false),
          editBtn: this.validData(this.permission.work_price_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
      created(){
        this.query.isActive = '是';
      },
    methods: {
        updateActive(row) {
            this.loading = true;
            updateActive(row.id).then(res => {
                if (res.data.success) {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: res.data.msg || "操作成功!"
                    });
                }
            }).catch(() => {
                this.loading = false;
            });
        },
      handleExport() {
        // const account = func.toStr(this.search.account);
        // const realName = func.toStr(this.search.realName);
        NProgress.start();
        exportBlob(
                `/blade-anwise/prod/work_price/export?${this.website.tokenHeader
                }=${getToken()}`, this.search
        ).then(res => {
          downloadXls(res.data, `生产单价${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
          NProgress.done();
        });
      },
      rowClassName({row, rowindex}) {
        if (row.isAssign ==='未审核') {
          return 'row-yellow';
        }
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleAdd(){
        userCompany().then(res => {
          if (res.data.success) {
            this.dept = res.data.data;
            if (!this.dept) {
              this.$message({
                type: "error",
                message: "用户无组织机构信息，请联系安伟工作人员！"
              });
            } else {
              let title="创建生产单价";
              let type='edit';
              this.$refs.workPriceForm.show({
                title,
                type
              })
            }
          }
        })
      },
      handleView(row){
        let title="查看生产单价";
        let type='view';
        const id = row.id;
        this.$refs.workPriceForm.show({
          id,
          title,
          type
        })
      },
      handleCopy(row){
        let title="复制生产单价";
        let type='copy';
        const id = row.id;
        this.$refs.workPriceForm.show({
          id,
          title,
          type,
          row
        })
      },
      handleEdit(row){
        editPrice(row.id).then(res=>{
          if (res.data.success) {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg || "更新成功!"
            });
          }
        })
      },
      rowAudit(row){
          this.loading = true;
        audit(row.id).then(res => {
            this.loading = false;
          if (res.data.success) {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg || "操作成功!"
            });
          }
        }).catch(() => {
            this.loading = false;
        });
      },
      rollbackAudit(row){
          this.loading = true;
        changeStatus(row.id, 2).then(res => {
            this.loading = false;
          if (res.data.success) {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg || "反审核成功!"
            });
          }
        }).catch(() => {
            this.loading = false;
        });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
          this.activeDateRange = [];
          this.search.activeDateStart = '';
          this.search.activeDateEnd = '';
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        handleDatePickerChange(value) {
            console.log(value);
            if (value) {
                this.search.activeDateStart = value[0];
                this.search.activeDateEnd = value[1];
            } else {
                this.search.createTimeStart = '';
                this.search.createTimeEnd = '';
            }
        },
    }
  };
</script>

<style>
  .row-yellow {
    background-color: rgb(255, 253, 230) !important;
    cursor: pointer;
  }
</style>
